package my.shadowsocks.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import my.shadowsocks.common.config.Config;
import my.shadowsocks.common.encryption.Crypt;
import my.shadowsocks.common.encryption.CryptFactory;

import java.util.List;

/**
 * @author fengbo
 * @date 2018/10/12
 */
public class BouncyCastleCodec extends MessageToMessageCodec<ByteBuf, ByteBuf> {

    private Crypt crypt;

    BouncyCastleCodec() {
        Config config = Config.getInstance();
        crypt = CryptFactory.get(config.getStringValue("method"), config.getStringValue("password"));
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) {
        byte[] encrypt = CryptUtils.encrypt(crypt, byteBuf);
        list.add(Unpooled.copiedBuffer(encrypt));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) {
        ByteBuf dataBuff = Unpooled.buffer();
        if (byteBuf.readableBytes() <= 0) {
            return;
        }
        byte[] decrypt = CryptUtils.decrypt(crypt, byteBuf);
        dataBuff.writeBytes(decrypt);
        list.add(dataBuff);
    }
}
